<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Loader;
use think\Request;

/**
 * 支付回调类
 **/
class Notify extends Controller
{
    /**
     * 回调处理：
     * 1：支付状态改为已支付
     * 2：修改优惠券为已使用状态
     * 3：分佣（分享官，城市合伙人）
     * */
    public function notice()
    {
        $data = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //业务处理代码请自行实现
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {

            //接收附加数据
            $json_attach = $data['attach'];
            $attach_arr = json_decode($json_attach, true);

            //订单号
            $order_sn = $data['out_trade_no'];

            //查询订单支付状态；0：未支付；1：已支付
            $is_pay = Db::name('order')->where(['pay_order_sn' => $order_sn])->value('is_pay');

            if ($is_pay == 0) {
                Db::startTrans();
                try {
                    $this->doGoodsOrder($order_sn);

                    echo 'SUCCESS';
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }

        }
    }

    /**
     * 按综合方式输出通信数据（后台异步返回信息专用）
     * @param integer $result 状态码
     * @param string  $msg    提示信息
     * @param array   $url    参考 url() 方法；链接：https://www.kancloud.cn/manual/thinkphp5/118041
     * @param int     $timer  跳转时间
     * @return      string
     */
    function adminReturn($result, $msg = '', $url = '', $timer = 1000)
    {
        if ($result == 1) {
            $message = [
                'result' => $result,
                'msg' => $msg,
                'url' => $url,
                'timer' => intval($timer)
            ];
        } else {
            $request = Request::instance();
            $token = $request->token();

            $message = [
                'result' => $result,
                'msg' => $msg,
                'url' => $url,
                'token' => $token,
                'timer' => intval($timer)
            ];
        }

        echo json_encode($message, JSON_UNESCAPED_UNICODE);
        exit;
    }

    public function testPay()
    {
        $order_sn = 'D24061412264881';
        if (empty($order_sn)) $this->adminReturn(2, '未查询到订单编号');

        $this->doGoodsOrder($order_sn);
    }

    /**
     * 商品订单支付成功处理业务逻辑
     * @param string $order_sn 支付订单号
     * */
    public function doGoodsOrder($order_sn)
    {
        $order_info = Db::name('order')->where(['pay_order_sn' => $order_sn])->find();

        $order_id = $order_info['id'];
        $shop_id = $order_info['shop_id'];

        $time = time();

        $hx_qr = '';
        if ($order_info['send_type'] == 1) {
            // 待配送
            $status = 2;
        } elseif ($order_info['send_type'] == 2) {
            // 待自提
            $status = 9;
        } elseif ($order_info['send_type'] == 3) {
            // 待核销
            $status = 10;
            $hx_qr = createOrderHxQr($order_id);
        }

        // 1：修改订单支付状态
        $update_order_data = [
            'is_pay' => 1,
            'status' => $status,
            'hx_qr' => $hx_qr,
            'pay_time' => $time,
            'update_time' => $time
        ];

        Db::name('order')->where(['id' => $order_id])->update($update_order_data);

        //        // 2：修改优惠券为已使用状态
        //        if ($user_coupon_id) Db::name('user_coupon')->where(['id' => $user_coupon_id])->update(['status' => 2, 'update_time' => $time]);

        $vice_order_list = Db::name('vice_order')->where(['order_id' => $order_id])->select();
        if ($vice_order_list) {
            foreach ($vice_order_list as &$v) {
                // 3：增加销量
                Db::name('goods')->where(['id' => $v['goods_id']])->setInc('sales_count', $v['count']);

                // 4：减库存
                if ($order_info['is_business'] == 0 || date('Y-m-d') == explode(' ', $order_info['arrive_time'])[0]) Db::name('goods')->where(['id' => $v['goods_id']])->setDec('stock_count', $v['count']);
            }
        }

        // 打印订单
        $content = getPayOrderPrinterContent($order_id);
        $printer_sn = Db::name('shop')->where(['id' => $shop_id])->value('printer_sn');
        if ($content && $printer_sn) {
            Loader::import('printer/Api', EXTEND_PATH);
            $obj = new \Api(C('PRINTER_APPID'), C('PRINTER_APPSECRET'));
            $obj->prints($printer_sn, $content);
        }

        /*if ($use_integral = $order_info['use_integral']) {
            // 5：积分扣除（下单有积分扣除即：积分抵扣商品）
            $integral_data = [
                'user_id' => $user_id,
                'shop_id' => $shop_id,
                'integral' => '-' . $use_integral,
                'type' => 2,
                'order_id' => $order_id,
                'create_time' => $time
            ];
            Db::name('integral_log')->insert($integral_data);

            Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->setDec('integral', $use_integral);
        }*/

        // 微信支付且赠送积分
        /*$send_integral = $order_info['send_integral'];
        if($order_info['pay_type'] == 1 && $send_integral){
            // 6：赠送积分
            $integral_data = [
                'user_id' => $user_id,
                'shop_id' => $shop_id,
                'integral' => $send_integral,
                'type' => 1,
                'order_id' => $order_id,
                'create_time' => $time
            ];
            Db::name('integral_log')->insert($integral_data);

            Db::name('customer')->where(['user_id' => $user_id, 'shop_id' => $shop_id])->setInc('integral', $send_integral);

            $msg_data = [
                'user_id' => $user_id,
                'shop_id' => $shop_id,
                'title' => '购买商品赠送积分',
                'content' => '购买商品赠送积分',
                'create_time' => $time
            ];
            Db::name('msg')->insert($msg_data);
        }*/
    }
}